<template>
	<a-modal
		:title="handleType === 'add' ? '增加cp' : '修改cp'"
		:visible="visible"
		:confirm-loading="confirmLoading"
		@ok="handleSubmit"
		@cancel="handleCancel"
	>
		<a-form-model ref="incpForm" :model="form" :rules="rules" v-bind="layout">
			<a-form-model-item label="物流公司名称" prop="name" has-feedback>
				<a-input v-model="form.name" placeholder="请输入" />
			</a-form-model-item>

			<!-- <a-form-model-item label="手机号码" prop="phone" has-feedback>
				<a-input v-model="form.phone" />
			</a-form-model-item> -->

			<a-form-model-item label="营业开始时间" prop="start_time" has-feedback>
				<a-time-picker
					placeholder="请选择"
					@change="onChangeStartTime"
					v-model="startDefaultTime"
					format="HH:mm"
				/>
			</a-form-model-item>

			<a-form-model-item label="营业结束时间" prop="end_time" has-feedback>
				<a-time-picker
					placeholder="请选择"
					@change="onChangeEndTime"
					v-model="endDefaultTime"
					format="HH:mm"
				/>
			</a-form-model-item>

			<a-form-model-item label="状态" prop="status" has-feedback>
				<a-select
					style="width: 120px"
					@changeStatus="changeStatus(item.key)"
					placeholder="请选择"
					v-model="form.status"
				>
					<a-select-option
						v-for="(item, index) in statusList"
						:value="item.key"
						:key="index"
					>
						{{ item.text }}
					</a-select-option>
				</a-select>
			</a-form-model-item>

			<!-- <a-form-model-item label="用户名" prop="user_name" has-feedback>
				<a-input v-model="form.user_name" />
			</a-form-model-item> -->

			<a-form-model-item label="所属市场">
				<a-select
					allowClear
					v-model="form.market_id"
					@change="handleMarketChange"
					placeholder="请选择"
				>
					<a-select-option
						v-for="(item, index) in form.marketData"
						:key="index"
						:value="item.id"
					>
						{{ item.name }}
					</a-select-option>
				</a-select>
			</a-form-model-item>

			<a-form-model-item label="运营区域" prop="map_area_list">
				<a-select
					mode="multiple"
					allowClear
					@change="changeAreaData"
					placeholder="请选择"
					v-model="form.map_area_list"
				>
					<a-select-option
						v-for="(item, index) in areaList"
						:value="item.map_area_id"
						:key="index"
					>
						{{ item.map_area_name }}
					</a-select-option>
				</a-select>
			</a-form-model-item>

			<!-- :disabled="handleType !== 'add'" -->
			<!-- <div slot="footer">
				<a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
					<a-button @cancel="handleCancel"> 取消 </a-button>
					<a-button
						type="primary"
						style="margin-left: 10px"
						@ok="handleSubmit"
						:disabled="checkRequire(getObj(Object.keys(rules)))"
					>
						确定
					</a-button>
				</a-form-model-item>
			</div> -->
		</a-form-model>
	</a-modal>
</template>

<script>
	// import User from "@/api/user"
	import moment from "moment"
	// import momentUtil from "@/utils/day"
	import incpHttp from "@/api/incp"
	import salemarket from "@/api/salemarket"
	import areaHttp from "@/api/area"
	const lodash = require("lodash")
	export default {
		name: "handleForm",
		data() {
			this.id = null
			this.handleType = null
			this.statusList = [
				{
					key: 1,
					text: "正常",
				},
				{
					key: 0,
					text: "停用",
				},
				{
					key: -1,
					text: "冻结",
				},
			]
			return {
				// value1: null,
				// value2: null,

				endDefaultTime: undefined,
				startDefaultTime: undefined,
				areaList: [],
				// flag: true,

				title: "增加",
				layout: {
					labelCol: { span: 6 },
					wrapperCol: { span: 12 },
				},

				ModalText: "Content of the modal",
				visible: false,
				confirmLoading: false,
				form: {
					code: "",
					created_at: "",
					created_at_show: "",
					end_time: "",
					end_time_show: "",
					id: "",
					market_id: undefined,
					// map_area_id: undefined,
					map_area_list: [],
					start_time: "",
					start_time_show: "",
					status_show: "",
					updated_at: "",
					updated_at_show: "",
					// ==============================

					name: undefined,
					user_name: undefined,
					// phone: "",
					// start_time: "",
					// end_time: "",
					status: undefined,
					market_name_show: "",
					marketData: [],
				},
				rules: {
					name: [{ required: true, trigger: "change", message: "cp名必填" }],
					// phone: [{ required: true, trigger: "change", message: "手机号必填" }],
					start_time: [
						{ required: true, trigger: "change", message: "营业开始时间必填" },
					],

					end_time: [
						{ required: true, trigger: "change", message: "营业结束时间必填" },
					],
					status: [{ required: true, trigger: "change", message: "请选择状态" }],
					market_name_show: [
						{ required: true, trigger: "change", message: "请填写所属市场" },
					],

					map_area_list: [
						{ required: true, trigger: "change", message: "请选择运营区域" },
					],
				},
			}
		},

		watch: {
			visible(newVal) {
				if (newVal == false) this.resetFormFields()

				// 获取批发市场列表
				// this.getMarketList()
			},
		},
		methods: {
			moment,
			async getAreaList(market_id) {
				console.log(market_id)

				await areaHttp
					.query({
						market_id,
					})
					.then((response) => {
						console.log("区域列表数据", response)
						if (response.code !== 1) {
							this.$message.warning(response.message)
							return
						}
						// this.flag = false
						// this.form.map_area_id = undefined
						// setTimeout(() => {
						// 	this.flag = true
						// })
						this.areaList = []
						response.data.forEach((element) => {
							this.areaList.push({
								map_area_id: element.id,
								map_area_name: element.name,
							})
						})
					})
			},

			handleMarketChange(market_id) {
				console.log(`selected ${market_id}`)
				this.areaList = []
				// this.form.map_area_id = undefined
				this.form.map_area_list = []
				this.getAreaList(market_id)
				// this.form.incp_id = ""
				// this.form.market_id = value
				// // 获取市场下场内CP列表
				// this.getIncp(value)
			},
			// getAreaList(market_id) {
			// 	areaHttp
			// 		.select(market_id)
			// 		.then((response) => {
			// 			console.log("区域列表", response)
			// 		})
			// 		.catch((e) => {
			// 			console.log(e)
			// 		})
			// },
			changeAreaData(map_area_list) {
				console.log(map_area_list)

				this.form.map_area_list = map_area_list
			},
			onChangeStartTime(time, timeString) {
				console.log(time, timeString)
				if (!time) {
					return
				}
				// this.form.start_time = timeString
				// console.log(time, timeString)
				// this.value1 = time
				// this.startDefaultTime = time

				this.form.start_time = time.format("HH:mm")
			},
			onChangeEndTime(time, timeString) {
				if (!time) {
					return
				}
				this.form.end_time = time.format("HH:mm")
				// console.log(time, timeString)
				// this.value2 = time
			},
			formatStamp(timeStr) {
				console.log(
					timeStr,
					this.moment(this.$formatDate("h:m", +new Date(timeStr)), "HH:mm")
				)
				return this.moment(this.$formatDate("h:m", +new Date(timeStr)), "HH:mm")
			},
			getObj(rulesKeyArr) {
				let obj = {}
				for (let key of rulesKeyArr) {
					obj[key] = this.form[key]
				}
				return obj
			},
			checkRequire(obj) {
				return this.$isEmpty(obj)
			},

			changeStatus(value) {
				this.form.status = value
			},

			resetFormFields() {
				this.form = {
					code: "",
					created_at: "",
					created_at_show: "",
					end_time: "",
					end_time_show: "",
					id: "",
					market_id: undefined,
					// map_area_id: undefined,
					map_area_list: [],
					start_time: "",
					start_time_show: "",
					status_show: "",
					updated_at: "",
					updated_at_show: "",
					// ==============================
					name: undefined,
					user_name: undefined,
					// phone: "",
					// start_time: "",
					// end_time: "",
					status: undefined,
					market_name_show: "",
					marketData: [],
				}
				// this.value1 = null
				// this.value2 = null

				// this.flag = false
				// setTimeout(() => {
				// 	this.flag = true
				// })
				this.areaList = []
				// this.form.map_area_id = undefined

				this.startDefaultTime = undefined
				this.endDefaultTime = undefined
				// this.$refs.incpForm.resetFields()
			},

			handleSubmit() {
				this.handleType === "add" ? this.addIncp() : this.updateIncp()
			},
			addIncp() {
				let _this = this
				_this.$refs.incpForm.validate((err, values) => {
					// 验证表单没错误
					if (err) {
						_this.confirmLoading = true
						// if (typeof this.form.map_area_id === "object") {
						// 	this.form.map_area_ids = [...this.form.map_area_id]
						// } else {
						// 	this.form.map_area_ids = [this.form.map_area_id]
						// }
						// delete this.form.map_area_id
						_this.form = lodash.omit(_this.form, ["marketData"])
						incpHttp
							.create(this.$removeField(_this.form))
							.then((res) => {
								_this.confirmLoading = false
								if (res.code == 1) {
									_this.$message.success("添加成功")
									_this.$emit("handleOk")
									setTimeout(() => {
										_this.visible = false
									}, 500)
								}
							})
							.catch((e) => {
								_this.confirmLoading = false
							})
					}
				})
			},

			updateIncp() {
				let _this = this
				_this.$refs.incpForm.validate((err, values) => {
					console.log(err, values)
					// 验证表单没错误
					if (err) {
						console.log(1)
						_this.confirmLoading = true
						// if (typeof this.form.map_area_id === "object") {
						// 	this.form.map_area_ids = [...this.form.map_area_id]
						// } else {
						// 	this.form.map_area_ids = [this.form.map_area_id]
						// }

						// delete this.form.map_area_id
						this.form = lodash.omit(_this.form, ["marketData"])
						console.log(2, incpHttp)
						incpHttp
							.update(
								this.id,
								this.$removeField({ ..._this.form, market_name_show: "" })
							)
							.then((res) => {
								_this.confirmLoading = false
								if (res.code == 1) {
									_this.$message.success("修改成功")
									_this.$emit("handleOk")
									setTimeout(() => {
										_this.visible = false
									}, 500)
								}
							})
							.catch((e) => {
								_this.confirmLoading = false
								_this.visible = false
							})
							.finally(() => {
								_this.confirmLoading = false
								_this.visible = false
							})
					}
				})
			},
			showModal(type, record) {
				console.log(type, record)
				this.handleType = type
				if (type === "update") {
					Object.keys(this.form).forEach((key) => {
						this.form[key] = record[key]
					})
					this.id = record.id
					// ====================页面显示数据============================
					// this.value1 =
					// 	this.form.start_time.length <= 5
					// 		? this.moment(this.form.start_time, "HH:mm")
					// 		: this.formatStamp(this.form.start_time)
					// this.value2 =
					// 	this.form.end_time.length <= 5
					// 		? this.moment(this.form.end_time, "HH:mm")
					// 		: this.formatStamp(this.form.end_time)

					console.table({
						startDefaultTime: this.form.start_time,
						endDefaultTime: this.form.end_time,
					})
					if (this.form.start_time && this.form.end_time) {
						this.startDefaultTime = this.moment(this.form.start_time, "HH:mm")
						this.endDefaultTime = this.moment(this.form.end_time, "HH:mm")
					} else {
						this.startDefaultTime = undefined
						this.endDefaultTime = undefined
					}

					// ====================传递到后端数据============================
					// this.form.start_time =
					// 	this.form.start_time.length <= 5
					// 		? this.form.start_time
					// 		: this.$formatDate("h:m", +new Date(this.form.start_time))
					// this.form.end_time =
					// 	this.form.end_time.length <= 5
					// 		? this.form.end_time
					// 		: this.$formatDate("h:m", +new Date(this.form.end_time))

					// this.getAreaList(record.market_id)

					// this.areaList = record.map_area_list
					// 	? record.map_area_list.map((item) => {
					// 			return {
					// 				map_area_id: item.id,
					// 				map_area_name: item.name,
					// 			}
					// 	  })
					// 	: []

					this.form.market_id = record.market_id
					// this.form.map_area_id = record.map_area_id
					this.form.map_area_list = []
					if (record.map_area_list && record.map_area_list.length > 0) {
						this.form.map_area_list = record.map_area_list.map((item) => item.id)
					}

					this.getAreaList(record.market_id)

					// this.getMarketList()
				} else if (type === "add") {
					// this.$refs.incpForm.resetFields()
				}

				this.getMarketList()
				this.visible = true
			},
			async getMarketList(params = {}) {
				// this.resetFormFields()
				this.form.marketData = []

				await salemarket.query(params).then((response) => {
					console.log("市场列表数据", response)
					if (response.code !== 1) {
						this.$message.warning(response.message)
						return
					}

					if (response.data && response.data.length > 0) {
						this.form.marketData = response.data.map((item) => {
							return {
								id: item.id,
								name: item.name,
							}
						})
					}
				})
			},

			handleCancel(e) {
				this.visible = false
			},
		},
	}
</script>

<style>
</style>